package com.xiemulei.gulimall.search.service.impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.BulkRequest;
import co.elastic.clients.elasticsearch.core.BulkResponse;
import co.elastic.clients.elasticsearch.core.bulk.BulkResponseItem;
import com.xiemulei.common.to.es.SkuEsModel;
import com.xiemulei.gulimall.search.constant.EsConstant;
import com.xiemulei.gulimall.search.service.ProductSaveService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service("productSaveService")
public class ProductSaveServiceImpl implements ProductSaveService {
    @Resource
    ElasticsearchClient esClient;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        //1、给 es 中建立索引，product。建立好映射关系

        //2、保存数据
        BulkRequest.Builder br = new BulkRequest.Builder();
        for (SkuEsModel skuEsModel : skuEsModels) {
            br.operations(op -> op
                    .index(idx -> idx
                            .index(EsConstant.PRODUCT_PREFIX)
                            .id(skuEsModel.getSkuId().toString())
                            .document(skuEsModel)
                    )
            );
        }
        BulkResponse result = esClient.bulk(br.build());

        // 如果批量错误
        if (result.errors()) {
            List<String> collect = result.items().stream().map(BulkResponseItem::id).collect(Collectors.toList());
            log.error("商品上架错误:{}", collect);
            return false;
        } else {
            return true;
        }

    }
}
